package com.google.webrtc.apmdemo.file;

import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author df-bolin
 * @createTime 2024/1/22 15:22
 * <p>
 * 1，检查原始mic音频数据是否是有效音频
 * 2，保存音频能力（原始音频&AEC后音频）
 */
public enum AudioDataSaver {

    getInstance;


    private boolean dumpMicEnable = true;

    private String TAG = "AudioDataFilter";
    public String pcmFolder = "/sdcard/pcm/1/";//mic音频保存目录
    private FileOutputStream mOriginalPcmFileWriter;


    private Handler cacheHandler;

    AudioDataSaver() {
        HandlerThread thread = new HandlerThread(TAG);
        thread.start();
        cacheHandler = new Handler(thread.getLooper());
    }

    public void saveMicDataIfneed(byte[] data) {
        cacheHandler.post(new Runnable() {
            @Override
            public void run() {
                saveMicData(data);
            }
        });

    }

    /**
     * 保存录音机mic原始音频
     *
     * @param data
     */
    private void saveMicData(byte[] data) {
        try {
            if (dumpMicEnable) {
                if (mOriginalPcmFileWriter == null) {
                    String path = buildPath("_mic");
                    File file = new File(path);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    mOriginalPcmFileWriter = new FileOutputStream(path);
                    Log.w(TAG, "savePcmDatatoLocal,fullName:" + path);
                }
                mOriginalPcmFileWriter.write(data);
            } else {
                if (mOriginalPcmFileWriter != null) {
                    mOriginalPcmFileWriter.flush();
                    mOriginalPcmFileWriter.close();
                    Log.w(TAG, "mOriginalPcmFileWriter.close");
                }
                mOriginalPcmFileWriter = null;
            }
        } catch (Exception ex) {
            Log.w(TAG, "Exception:" + ex.getLocalizedMessage());
            mOriginalPcmFileWriter = null;
        }

    }


    public void closeDataSaver(){
        dumpMicEnable = false;
    }

    public void openDataSaver(){
        dumpMicEnable = true;
    }




    /**
     * 带时间的路径
     * @param tag
     * @return
     */
    private String buildPath(String tag) {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-HH点_mm分_ss");
        String fullName = pcmFolder + sdf.format(d) + tag + ".pcm";
        return fullName;
    }








 }